package com.lzq.course.business.controller.web;

import com.alibaba.fastjson.JSON;
import com.lzq.course.server.dto.LoginMemberDto;
import com.lzq.course.server.dto.MemberDto;
import com.lzq.course.server.dto.ResponseDto;
import com.lzq.course.server.service.MemberService;
import com.lzq.course.server.util.UuidUtil;
import com.lzq.course.server.util.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController("webMemberController")
@RequestMapping("/web/member")
public class MemberController {

    private final static Logger LOG = LoggerFactory.getLogger(MemberController.class);
    public static final String BUSINESS_NAME = "会员";

    @Resource
    private MemberService memberService;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 注册
     * @param memberDto
     * @return
     */
    @PostMapping("/register")
    public ResponseDto register(@RequestBody MemberDto memberDto) {

        //保存校验
        ValidatorUtil.require(memberDto.getMobile(), "手机号");
        ValidatorUtil.length(memberDto.getMobile(),"手机号", 1, 11);
        ValidatorUtil.require(memberDto.getPassword(), "密码");
        ValidatorUtil.length(memberDto.getName(),"昵称", 1, 50);
        ValidatorUtil.length(memberDto.getPhoto(),"头像url", 1, 200);

        memberDto.setRegisterTime(new Date()); // 注册时间
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes())); // 密码二次加密

        ResponseDto responseDto = new ResponseDto();
        memberService.save(memberDto);

        responseDto.setContent(memberDto);
        return responseDto;
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public ResponseDto login(@RequestBody MemberDto memberDto) {
        LOG.info("用户登录开始");
        memberDto.setPassword(DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes()));
        ResponseDto responseDto = new ResponseDto();
        // 1.效验验证码
        String imageCode = (String) redisTemplate.opsForValue().get(memberDto.getImageCodeToken());
        LOG.info("从redis中获取到的验证码：{}", imageCode);
        if (StringUtils.isEmpty(imageCode)) {
            LOG.info("用户登录失败，图片验证码过期");
            responseDto.setMessage("图片验证码过期");
            return responseDto;
        }
        if (!imageCode.equalsIgnoreCase(memberDto.getImageCode())) {
            LOG.info("用户登录失败，验证码错误");
            responseDto.setSuccess(false);
            responseDto.setMessage("图片验证码错误");
            return responseDto;
        } else {
            // 验证通过 移除验证码
            redisTemplate.delete(memberDto.getImageCodeToken());
        }
        // 2.效验用户名密码
        LoginMemberDto loginMemberDto = memberService.login(memberDto);
        String token = UuidUtil.getShortUuid();
        loginMemberDto.setToken(token);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginMemberDto), 3600, TimeUnit.SECONDS);
        responseDto.setContent(loginMemberDto);
        return responseDto;
    }

    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout/{token}")
    public ResponseDto logout(@PathVariable String token) {
        ResponseDto resourceDto = new ResponseDto();
        redisTemplate.delete(token);
        return resourceDto;
    }
}
